<template>
  <el-dialog
    :visible='visible'
    :title="$t('page.import')"
    width='500px'
    @close='handleClose'
  >
    <el-form ref='fileForm' style='margin-bottom: 0px;' :rules='fileRules' :model='fileModel' @submit.prevent.native>
      <el-upload
        ref='upload'
        :before-upload='beforeAvatarUpload'
        :on-change='handleChange'
        :on-remove='handleRemove'
        :on-error='handleError'
        :file-list='fileModel.fileList'
        action
        :http-request='handleUploadFile'
        :headers='headers'
        :auto-upload='false'
        :limit='1'
        :multiple='false'
        drag
        accept='.xls, .xlsx, .txt'
        style='text-align: center;'
      >
      <!-- TODO: -->
      <template #tip>
        <div style='width: 360px; align: center;'>
          <i class='el-icon-upload' />
          <div class='el-upload__text'>
            {{ $t('batch.upload_dragTip') }}
            <em>{{ $t('batch.clickUpload') }}</em>
          </div>
          
            <div class='el-upload__tip'>{{ $t('common.excel_upload_tip') }}</div>
        </div>
      </template>
        <el-form-item prop='fileList'>
          <el-input v-show='false' ref='fileInput' :model='fileModel.fileList' />
        </el-form-item>
      </el-upload>
    </el-form>
    <div style='text-align: center;'>
      <el-button
        type='text'
        icon='el-icon-download'
        style='text-decoration:underline;'
        @click='downloadTxt'
      >{{ $t('common.download_text_template') }}
      </el-button>
      <el-button
        type='text'
        icon='el-icon-download'
        style='text-decoration:underline;'
        @click='downloadExcel'
      >{{ $t('common.download_excel_template') }}
      </el-button>
    </div>
    <template #footer>
    <span class='dialog-footer'>
        <el-checkbox style='float: left' v-model='forceImport'>
        {{ $t('common.import_continue_when_err_tip') }}
        <el-popover
          popper-class='white-on-black'
          placement='right'
          title=''
          width='400'
          trigger='hover'>
          <span>{{ $t('common.import_continue_when_err_desc') }}</span>
          <template #reference>
           <i class='el-icon-question' />
          </template>
        </el-popover>
      </el-checkbox>
        <el-button size='small' @click='cancelUpload'>{{ $t('page.cancel') }}</el-button>
        <el-button type='primary' :loading='loading' size='small' @click='submitUpload()'>{{ $t('page.confirm')
          }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { addBatchDeviceByFile } from '@/api/batch'
import { getToken } from '@/utils/auth'
import axios from 'axios'
import store from '@/store'

export default {
  props: {
    visible: Boolean,
    batchId: String
  },
  data() {
    var validateFile = (rule, value, callback) => {
      if (value === undefined || value.length === 0) {
        return callback(new Error(this.$t('common.upload_file_tip')))
      } else {
        return callback()
      }
    }
    return {
      fileModel: { 'fileList': [] },
      loading: false,
      fileRules: {
        fileList: [
          {
            required: true,
            validator: validateFile,
            trigger: 'blur'
          }
        ]
      },
      forceImport: false,
      fileList: [],
      headers: { 'WEB-TOKEN': getToken() }
    }
  },
  computed: {},
  methods: {
    handleClose() {
      this.loading = false
      this.$refs['fileForm'].resetFields()
      this.fileModel.fileList = []
      this.$emit('update:model-value', false)
    },
    // 文件上传成功的钩子函数
    handleAvatarSuccess(res, file) {
      this.fileList = []
      this.$emit('fileImportErrInfo', res)
      this.loading = false
      this.handleClose()
    },
    beforeAvatarUpload(file) {
      var testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const extension = testmsg === 'xls'
      const extension2 = testmsg === 'xlsx'
      const extension3 = testmsg === 'txt'
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2 && !extension3) {
        this.$message({
          message: this.$t('batch.tip_file_type_error'),
          type: 'warning'
        })
        this.loading = false
        return false
      }
      if (!isLt5M) {
        this.$message({
          message: this.$t('batch.tip_file_exced_5M'),
          type: 'warning'
        })
        this.loading = false
        return false
      }
      return (extension || extension2 || extension3) && isLt5M
    },
    handleChange(file, fileList) {
      this.fileModel.fileList = fileList.slice(-1)
      this.$refs['fileForm'].validate()
    },
    // 删除文件之前的钩子函数
    handleRemove(file, fileList) {
      // this.file_importVisible = true
      this.fileModel.fileList = []
      this.$refs['fileForm'].validate()
    },
    handleError(err) {
      // 当上传失败时，弹出提示
      var result = JSON.parse(err.message)
      this.$message.error(result.message)
      this.loading = false
    },
    handleUploadFile() {
      const formdata = new FormData()
      formdata.append('file', this.fileModel.fileList[0].raw)
      formdata.append('forceImport', this.forceImport)
      addBatchDeviceByFile({ batchId: this.batchId }, formdata).then(res => {
        console.log("aa")
        this.handleAvatarSuccess(res, null)
      }).catch(this.$confirmError).finally(() => {
        this.loading = false
      })
    },
    cancelUpload() {
      this.handleClose()
    },
    submitUpload() {
      this.$refs['fileForm'].validate((valid) => {
        if (valid) {
          this.actionType = 'add'
          this.loading = true
          this.$refs.upload.submit()
        }
      })
    },
    downLoad(url, fileName, params) {
      axios({
        method: 'get',
        url: url,
        responseType: 'blob',
        headers: {
          'WEB-TOKEN': getToken(),
          LANG:
            localStorage.getItem(store.state.user.keys.storage.lang) || 'en-US'
        },
        params: params
      }).then(({ data }) => {
        if (data) {
          var url = window.URL.createObjectURL(data)
          var a = document.createElement('a')
          a.href = url
          a.download = fileName
          a.click()
        } else {
          this.$message.error('Download error')
        }
      }).catch(this.$confirmError)
    },
    downloadExcel() {
      this.downLoad(import.meta.env.VITE_APP_BASE_API + '/online/management/admin/batch/export-template?type=IMPORT', 'Devices-import-template.xls')
    },
    downloadTxt() {
      this.downLoad(import.meta.env.VITE_APP_BASE_API + '/online/management/admin/batch/export-txt-template?type=IMPORT', 'Devices-import-template.txt')
    }
  }
}
</script>

